package de.slothsoft.wasbinich.android.database.webservice;

import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import de.slothsoft.wasbinich.android.R;
import de.slothsoft.wasbinich.android.util.ActivityUtil;
import de.slothsoft.wasbinich.core.ApplicationInfo;
import de.slothsoft.wasbinich.core.database.ApplicationBean;
import de.slothsoft.wasbinich.core.database.DatabaseException;
import de.slothsoft.wasbinich.core.database.DatabaseExceptionCode;
import de.slothsoft.wasbinich.core.database.webservice.AbstractWebserviceApplicationBean;
import de.slothsoft.wasbinich.core.database.webservice.RestCommunicator;

public class WebserviceApplicationBean extends AbstractWebserviceApplicationBean implements ApplicationBean {

    public WebserviceApplicationBean(RestCommunicator communicator) {
	super(communicator);
    }

    @Override
    public ApplicationInfo getClientInfo() throws DatabaseException {
	Activity context = ActivityUtil.getCurrentActivity();

	ApplicationInfo info = new ApplicationInfo();
	info.version = context == null ? "x.x.x" : getClientVersion(context); //$NON-NLS-1$
	info.pictureCount = -1;
	info.supportedLanguages = context == null ? new Locale[0] : parseLocales(((Context) context).getResources()
		.getStringArray(R.array.pref_language_values));
	return info;
    }

    private String getClientVersion(Context context) throws DatabaseException {
	try {
	    PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
	    return pInfo.versionName;
	} catch (NameNotFoundException e) {
	    throw new DatabaseException(DatabaseExceptionCode.UNKNOWN, ActivityUtil.getCurrentActivity().getString(
		    R.string.error_could_not_get_version), e);
	}
    }

}
